package com.jm.service.impl;

import com.jm.common.conf.datasource.DynamicDataSource;
import com.jm.common.tool.exception.ErrorException;
import com.jm.model.SysUser;
import com.jm.service.i.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author kong
 */
@Service
@Slf4j
public class TestDsService {
    private final SysUserService userService;

    @Autowired
    public TestDsService(SysUserService userService) {
        this.userService = userService;
    }

    @Transactional(rollbackFor = Exception.class)
    public void test() {
        //手动切换数据源
        DynamicDataSource.set("slave");
        this.test1();
        DynamicDataSource.set("master");
        this.test2();
        //测试数据回滚
        throw new ErrorException("");
    }

    private void test2() {
        this.userService.save(new SysUser().setUsername("master"));
    }

    private void test1() {
        this.userService.save(new SysUser().setUsername("slave"));
    }

}
